<template>
  <div class="lc_wrap"  >
    <el-row class="trendanalysis">

      <!-- 左侧树 -->
      <el-col :span="leftWidth">
        <div class="box treeBox">
          <basic-container>
            <lcTree @ready="ready" :deviceType="3"></lcTree>
          </basic-container>
        </div>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :span="rightWidth" class="table-wrapper" style="position: relative" v-loading="loading">
        <overlay @changeTreeBox="changeTreeBox"></overlay>
        <basic-container>

          <!-- 自定义搜索 -->
          <div class="search-tools">
            <div class="search-left">

              <!-- 月 （dateType==4）-->
              <div>
                <el-date-picker 
                  v-model="dateTime" 
                  type="month" 
                  size="small" 
                  value-format="yyyy-MM"
                  :picker-options="pickerOption" 
                  placeholder="选择月份" 
                  :clearable='false'>
                </el-date-picker>
              </div>

              <!-- 油烟因子（油烟浓度、悬浮颗粒物、非甲烷总氢） -->
              <div style="margin-left:20px;">
                <el-select size="small" v-model="gene">
                  <el-option 
                    v-for="(item, index) in geneList" 
                    :key="index" 
                    :label="item.alias"
                    :value="item.factorCode">
                  </el-option>
                </el-select>
              </div>
            </div>

            <!-- 搜索按钮 -->
            <div class="search-right">
              <div class="searcg-btns">
                <el-button 
                  type="primary" 
                  size="small" 
                  icon="el-icon-search" 
                  @click="search">
                  搜 索
                </el-button>
              </div>
            </div>

          </div>

          <!-- 暂无数据 -->
          <noData v-if="isEmpty"></noData>

          <!-- echarts -->
          <div v-else style="height:92%;">

            <!-- 折柱图 -->
            <e-chart 
              autoresize 
              :options="lineBarOptions" 
              style="height:27%;" 
              id="k_chart" 
              @click="searchByDay">
            </e-chart>

            <!-- 分隔线 -->
            <el-divider content-position="center" style="height:6%;" >{{detailedDay}}</el-divider>

            <!-- 折线图（油烟浓度、悬浮颗粒物、非甲烷总氢） -->
            <e-chart autoresize :options="lineChartOptions" style="height:27%;"></e-chart>

            <!-- 风机、净化器运行状态 -->
            <e-chart autoresize :options="motionChartOptions" style="height:20%;"></e-chart>

            <!-- 在线达标率 -->
            <e-chart autoresize :options="rateChartOptions" style="height:20%;"></e-chart>

          </div>

        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getFactorList, getKLineChart, getLine, getWorkingStatus, getComplianceRate} from "@/api/loam/trendanalysis";
import {mapGetters} from "vuex";
import {dateFormat} from "@/util/date";
import lcTree from "@/components/common/tree.vue";
import noData from "@/components/common/noData";
import overlay from "@/components/common/overlay.vue";

export default {
  components: {
    lcTree,
    noData,
    overlay
  },
  data() {
    let _this = this

    return {
    	loading:false,
      isEmpty: true,
      lineBarOptions: {}, // 折柱图
      lineChartOptions: {}, // 折线图
      motionChartOptions: {}, // 风机、净化器运行状态
      rateChartOptions: {}, // 在线达标率
      leftWidth: this.$leftWidth,
      rightWidth: this.$rightWidth,
      data: [],
      dateTime: dateFormat(new Date(), 'yyyy-MM'),
      detailedDay: dateFormat(new Date(), 'yyyy-MM-dd'),
      pickerOption: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
      nodeId: null,
      deptInfoName: '',
      deptInfoId: '',
      geneList: [],
      gene: '',
      selectFactor: {},
      unit: '',
      interval: 59,
      kChartData: {xArray: [], yArray: []},
      monthData: [],
      chartData: {}
    };
  },
  computed: {
    ...mapGetters(["permission"])
  },
  methods: {
    // 左侧树加载完毕时间
    ready(val) {
      this.nodeId = val.key;
      this.deptInfoName = val.title;
      this.deptInfoId = val.key;
      this.dateTime = dateFormat(new Date(), 'yyyy-MM');
      let that = this;
      that.onLoad();
    },

    // 加载页面
    onLoad() {    	
      this.getLoamFactorList();
    },

    // 获取时间（到天）
    getDetailedDay() {
      var queryDay = null;
      var currentMonth = dateFormat(new Date(), 'yyyy-MM');
      if( this.dateTime === currentMonth ) {
        queryDay = dateFormat(new Date(), 'yyyy-MM-dd')
      } else {
        queryDay = this.dateTime + "-" + this.getLastDayOfMonth(this.dateTime.split("-")[0], this.dateTime.split("-")[1]);
      }
      return queryDay;
    },

    // 获取某年某月的最后一天
    getLastDayOfMonth(year, month){
      var date = new Date(year,month-1,'01');
      date.setDate(1);
      date.setMonth(date.getMonth() + 1);
      var cdate = new Date(date.getTime() - 1000*60*60*24);
      return cdate.getDate();
    },

    // 根据treeId（groupId）获取因子
    getLoamFactorList() {
    	this.loading=true
      getFactorList(this.deptInfoId).then(res => {
        this.geneList = res.data.data;
        this.gene = this.geneList[0].factorCode;
        this.unit = this.geneList[0].unit;
        this.selectFactor = this.geneList[0];
      }).then(() => {
        this.getKChart();
      })
    },
    

    // 折线图options
    initLineChart(groupData) {
      var option = {
        title: {
          text: '日排放趋势图',
          textStyle: {
            color: '#505b83',
            fontStyle: 'normal',
            fontWeight: 'bolder',
            fontSize: 14
          },
          top: 0,
          left:'46.5%'
        },      	
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
        },
        grid: {
          left: 60,
          right: 60,
          top: 40,
          bottom: 30,
        },
        xAxis: [{
          type: 'category',
          data: groupData.xarray,
          axisLabel: {
            interval: this.interval,
            color: '#ccc'
          },
          axisLine: {
            onZero: false,
            lineStyle: {
              color: '#505b83'
            }
          },
          axisTick: false
        }],
        yAxis: {
          type: 'value',
					name: `${this.selectFactor.alias} (${this.selectFactor.unit})`,
					nameLocation: 'middle',
					nameGap: 40,
					nameTextStyle:{
						color:'#505b83',
						fontSize:12									
					},
          scale: true,
          axisLabel: {
            formatter: '{value} ',
            color: '#333',
          },
          axisLine: {
            lineStyle: {
              color: '#505b83'
            }
          },
          axisTick: false,
          splitLine: {
            show: true,
            lineStyle: {
              color: '#374062',
              type: 'dashed'
            }
          },
          min: null
        },
        visualMap: [],
        series: [{
          data: groupData.yarray,
          type: 'line',
          smooth: 0.5,
          name: groupData.siteName
        }]
      }

      // 根据阈值（有无、正负）显示分隔线和区域
      var threshold = groupData.standardVal;
      if(!( threshold === "" || threshold === undefined || threshold === null || threshold === NaN || parseFloat(threshold) === NaN )) {
        var standardVal = parseFloat(threshold);
        option.yAxis.min = standardVal <= 0 ? standardVal - 1 : 0;
        option.visualMap = [{
          show: false,
          pieces: [{
            gt: standardVal,
            color: '#E56060'
          }, 
          {
            gt: standardVal<= 0 ? standardVal - 1 : 0,
            lte: standardVal,
            color: '#23D3A8'
          }]
        }];
        option.series[0]['markLine'] = {
          silent: true,
          lineStyle: {
            normal: {
              color: '#E56060'
            }
          },
          data: [{
              yAxis: standardVal
          }],
          label: {
            normal: {
              formatter: '阈值: {c}'
            }
          },
        };
      } else {
        option.series[0]["itemStyle"] = {
          normal:{
            color:'#23D3A8',
            lineStyle:{color:'#23D3A8'}
          }
        };
      }
      
      return option;
    },    
    
    initLineBarCharts(obj){
		    	this.lineBarOptions={		  
		        title: {
		          text: '月排放趋势图',
		          textStyle: {
		            color: '#505b83',
		            fontStyle: 'normal',
		            fontWeight: 'bolder',
		            fontSize: 14
		          },
		          top: 0,
		          left:'46.5%'
		        },  		    		
				    tooltip: {
				        trigger: 'axis',
				        axisPointer: {
				            type: 'cross',
				            crossStyle: {
				                color: '#999'
				            }
				        }
				    },
		        grid: {
		          left: 60,
		          right: 60,
		          top: 40,
		          bottom: 20
		        },		    
				    legend: {
				    	  right:52,
				        data: [
			            {
			                name:'每日浓度平均值',
			                icon:'image://./img/system/21.png'//格式为'image://+icon文件地址'，其中image::后的//不能省略
			            },
			            {
			                name:'每日浓度最大值',	
			            }	
		            ]
				    },
				    xAxis: [
				        {
				            type: 'category',
				            data: obj.xArray,
				            axisPointer: {
				                type: 'shadow'
				            }
				        }
				    ],
				    yAxis: [
				        {
				            type: 'value',
										name: `${this.selectFactor.alias} (${this.selectFactor.unit})`,
										nameLocation: 'middle',
										nameTextStyle:{
											color:'#505b83',
											fontSize:12																					
										},
										nameGap: 40,				            
				            axisLabel: {
				                formatter: '{value}'
				            },
					          axisLine: {
					            lineStyle: {
					              color: '#505b83'
					            }
					          },
					          axisTick: false,
					          splitLine: {
					            show: true,
					            lineStyle: {
					              color: '#374062',
					              type: 'dashed'
					            }
					          }				          
				        },
				        {
				            type: 'value',
				            name: '',
				            axisLabel: {
				                formatter: '{value}'
				            }
				        }
				    ],
						visualMap : null,				    
				    series: [
				        {
				            name: '每日浓度平均值',
				            type: 'bar',
				            data: obj.data1,			            
										itemStyle:{
	                      color: function(params) {
				                  if(Number(params.data.isAbnormal)>0){
				                  	return '#e66061'
				                  }else{
				                  	return '#23d2a7'
				                  }		
		                    }											
										},
				        },
				        {
				            name: '每日浓度最大值',
				            type: 'line',
				            data: obj.data2,				           
										itemStyle:{
	                      color: obj.markLine?'#e66061':'#23d2a7'											
										}
				        }
				    ]
				}        	
    	  if(obj.markLine){
    	  	 this.lineBarOptions.visualMap=[{
			          show: false,
			          seriesIndex:1,
			          pieces: [{
			            gt: Number(obj.markLine),
			            color: '#e66061'
			          }, 
			          {
			            gt: 0,
			            lte: Number(obj.markLine),
			            color: '#23d2a7'
			          }]
					 }]
    	  	 this.lineBarOptions.series[1].markLine={
		          silent: true,
		          lineStyle: {
		            normal: {
		              color: '#E56060',
		              opacity:0
		            }
		          },
		          data: [{
		              yAxis: obj.markLine          
		          }],
		          label: {		          	
		            normal: {
		            	show:false,
		              formatter: '阈值: {c}'
		            }
		          }    	  	 	
    	  	 }
    	  }	
    },

    // 月份K线图
    getKChart() {
      getKLineChart(this.deptInfoId, this.dateTime, this.selectFactor.deviceFactorId).then(res => {
        if(res.data.success !== true) {
          return;
        }
        this.isEmpty = false;        
        this.kChartData = {xArray: [], data1:[],data2: [],markLine:null,unit:null};
      	let arr=res.data.data
      	this.kChartData.markLine=arr[0].standardVal
      	this.kChartData.unit=arr[0].unit
      	arr.forEach(item=>{
      		this.kChartData.xArray.push(item.dataSatsTime)
      		let obj={
      			value:item.avgConc,
      			isAbnormal:item.isAbnormal,
      			dataSatsTime:item.dataSatsTime
      		}
      		let obj2={
      			value:item.maxConc,
      			dataSatsTime:item.dataSatsTime
      		}
      		this.kChartData.data1.push(obj)
      		this.kChartData.data2.push(obj2)
      	})
        this.initLineBarCharts(this.kChartData)

      }).then(() => {
        // 每次获取K线图时，都需要重新获取折线图
        this.detailedDay = this.getDetailedDay();
        this.getLineChart(this.detailedDay);
      });
    },

    // 趋势分析第二张图表（折线图）
    getLineChart(day) {
      getLine(this.gene, this.selectFactor.deviceFactorId, day, this.deptInfoId, 2).then(res => {
        let isArrs = []; 
        let isFlag = false;

        //判断yarray数组里面的值是否都为0或"-", 只要有一个是真正的值，则isFlag 为true
        for( var i = 0 ; i < res.data.data[0].yarray.length ; i++ ) {
          if(res.data.data[0].yarray[i] !== "" && res.data.data[0].yarray[i] !== "-") {
            isFlag = true;
            break;
          }
        }
        if(!isFlag) {
          isFlag = !isFlag;
        }

        if (isFlag) { 
          this.lineChartOptions = this.initLineChart(res.data.data[0]);
        }
      }).then(() => {
        this.getMotionChart(day);
      });
    },

    // 风机、净化器运行状态
    getMotionChart(day) {
      getWorkingStatus(this.deptInfoId, this.selectFactor.deviceFactorId, day).then(res => {
        if(res.data.success !== true) {
          return;
        }
        var motionData = this.formatMotionData(res.data.data);
        this.motionChartOptions = this.initMotionStateChart(motionData);
      }).then(() => {
        this.getOnlineRateChart(day);
      });
    },

    // 在线达标率
    getOnlineRateChart(day) {
      getComplianceRate(this.deptInfoId, this.selectFactor.deviceFactorId, day).then(res => {
        if(res.data.success !== true) {
          return;
        }
        var result = [];
        res.data.data.forEach(item => {
          var this_bar = {
            name: '',
            type: 'bar',
            stack: '总量',
            barCategoryGap: '0%',
            color: '',
            barWidth: '40',
            data: [1],
          };
          if(item === 0) {
            this_bar.name = '未统计';
            this_bar.color = '#D1D1D1';
          } else if(item === 1) {
            this_bar.name = '达标';
            this_bar.color = '#23D3A8';
          } else if(item === 2) {
            this_bar.name = '不达标';
            this_bar.color = '#E66061';
          }
          result.push(this_bar);
        });
        this.loading=false
        this.rateChartOptions = this.initOnlineRateChart(result);
      });
    },

    // 左侧树收缩、展开
    changeTreeBox() {
      this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
      this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
    },

    // 点击搜索按钮
    search() {
    	this.loading=true
      for (var i = 0; i < this.geneList.length; i++) {
        if (this.gene == this.geneList[i].factorCode) {
          this.unit = this.geneList[i].unit;
          this.selectFactor = this.geneList[i];
          break;
        }
      }
      this.getKChart();
    },

    // 点击K线图上的点位
    searchByDay(param) {
    	this.loading=true
      this.detailedDay = param.data.dataSatsTime;
      this.getLineChart(this.detailedDay);
    },

    // 按照日期从小到大排序
    loamSort(ob1, ob2) {
      if (ob1.dataSatsTime < ob2.dataSatsTime) {
        return -1;
      } else if (ob1.dataSatsTime > ob2.dataSatsTime) {
        return 1;
      } else {
        return 0;
      }
    },

    // 格式化K线图数据
    splitKChartData(rawData, choosedIndex) {
			var categoryData = [];
			var values = [];
			for (var i = 0; i < rawData.length; i++) {
				let xData = new Date(rawData[i].splice(0, 1)[0]);
				if (i == choosedIndex) {
					categoryData.push({
						value: xData.getDate(),
						textStyle: {
							fontSize: 13,
							fontWeight: 'bold',
							color: '#000'
						}
					});
				} else {
					categoryData.push({
						value: xData.getDate()
					});
				}
				values.push({
					value: rawData[i],
				});
			}
			return {
				categoryData: categoryData,
				values: values
			};
    },

    // 整合运行状态数据为chart需要的格式
    formatMotionData(data) { 
      var motionState = {xAxis: data.xAxis, yAxisGreen: [], yAxisYellow: [], yAxisGray: []};
      var allParams = ["yAxisGreen", "yAxisYellow", "yAxisGray"];
      var motionParams = ["yAxisGreen", "yAxisYellow"];

      // 将数值为0的数据全部替换为""(gray,green,yellow)
      allParams.forEach(param => {
        data[param].forEach((item, index2) => {
          if(item === "0") {
            motionState[param][index2] = "";
          } else {
            motionState[param][index2] = item;
          }
        });
      });

      // 风机、净化器运行状态整合
      motionParams.forEach(param => {
        for(var i = 0; i < motionState[param].length; i++) {
          if(motionState[param][i] === 1 && motionState[param][i - 1] === '') {
            motionState[param][i - 1] = '0';
          }
          if(motionState[param][i] === 1 && motionState[param][i + 1] === '') {
            motionState[param][i + 1] = '0';
          }
        }
      });

      // 都未运行状态整合
      for(var i = 0; i < motionState.yAxisGray.length; i++) {
        if(motionState.yAxisGray[i] === 1 && motionState.yAxisGray[i - 1] === '' && motionState.yAxisGray[i + 1] === '') {
          motionState.yAxisGray[i - 1] = '0';
          motionState.yAxisGray[i + 1] = '0';
        }
      }

      return motionState;
    },
    



    // 风机、净化器运行状态option
    initMotionStateChart(orgData) {
      for (let i = 0, len = orgData.yAxisGreen.length; i < len; i++) {
        if ("1" != orgData.yAxisGreen[i]) {
          continue;
        }
        orgData.yAxisYellow[i] = "";
      }
      return {
        title: {
          text: '工作状态',
          textStyle: {
            color: '#505b83',
            fontStyle: 'normal',
            fontWeight: 'bolder',
            fontSize: 14
          },
          top: 10,
          left:'47.5%'
        },
        grid: {
          left: 60,
          right: 60,
          top: 40,
          bottom:40          
        },
        legend: {
          show:true,
          selectedMode: false,
          icon: "square",
          data: ['风机运行', '净化器运行', '风机与净化器未运行'],
          right: 50,
          padding: [15,0,0,0]
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: orgData.xAxis,
          axisLabel: {
            interval: parseInt((orgData.xAxis.length / 24) - 1)
          }
        },
        yAxis: [{
          type: 'value',
          show: false
        }],
        series: [{
            name: '风机运行',
            type: 'line',
            areaStyle: {
              color: '#FFD54F',
              opacity: 0.93,
            },
            itemStyle: {
              opacity: 0,
              normal: {
                color: '#FFD54F'
              }
            },
            symbolSize: 0,
            data: orgData.yAxisYellow
          },
          {
            name: '净化器运行',
            type: 'line',
            areaStyle: {
              color: '#23D2A7',
              opacity: 0.93,
            },
            itemStyle: {
              opacity: 0,
              normal: {
                color: '#23D2A7'
              }
            },
            symbolSize: 0,
            data: orgData.yAxisGreen
          },
          {
            name: '风机与净化器未运行',
            type: 'line',
            areaStyle: {
              color: '#ccc',
              opacity: 0.93,
            },
            itemStyle: {
              opacity: 0,
              normal: {
                color: '#ccc'
              }
            },
            symbolSize: 0,
            data: orgData.yAxisGray
          }
        ]
      };
    },

    // 在线达标率option
    initOnlineRateChart(orgData) {
      return {
        title: {
          text: '在线达标率',
          textStyle: {
            color: '#505b83',
            fontStyle: 'normal',
            fontWeight: 'bolder',
            fontSize: 14
          },
          top: 10,
          left:'47%'
        },
        legend: {
          show:true,
          data: ['不达标','达标','未统计'],
          right: 50,
          icon: "square",
          padding: [15,0,0,0],
          color: ['#E66061', '#23D3A8', '#D1D1D1']
        },
        grid: {
          left: 50,
          right: 60,
          top: 40
        },
        xAxis: [{
          type: 'value',
          scale: true,
          splitLine: 'false',
          max: orgData.length,
          min: 0,
          splitNumber: orgData.length
        }, 
        {
          type: 'value',
          splitLine: 'false'
        }],
        yAxis: {
          type: 'category',
          show: false
        },
        series: orgData
      };
    }
  }
};
</script>
<style lang="scss" scoped>
*{box-sizing: border-box;}
.empty {
  position: absolute;
  left: 0;
  top: 20%;
  color: #ccc;
  right: 0;
  bottom: 20%;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #909399;
}

.map {
  width: 100%;
  height: 500px;
}

.box {
  height: 100%;
  margin-bottom: 0;
}

.search-left {
  display: flex;
  height: 33px;
  line-height: 33px;
}

.el-row {
  height: calc(100% - 20px);
}

.el-col {
  height: 100%;
  overflow: auto;
}

.search-tools {
  height: 49px;
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
}

.search-right {
  display: flex;
}

.search-tabs {
  height: 33px;
  display: flex;
  align-items: center;
  margin-right: 40px;
}



.el-divider{
  margin: 20px 0px !important;
}
</style>